#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
"""
    :author: 5km (十里)
    :url: https://www.smslit.top
    :copyright: © 2018 5km <5km@smslit.cn>
    :license: MIT, see LICENSE for more details.
"""
import argparse
from PIL import Image

parser = argparse.ArgumentParser(description='此工具可以将图片转换为字符画。')
parser.add_argument('file', help='待转换的图片路径')
parser.add_argument('-o', '--output', help='指定生成字符画的保存路径')
parser.add_argument(
    '-W',
    '--width',
    type=int,
    default=80,
    help='可以通过此参数指定图片转换大小到一定宽度，单位：像素，默认值：80')
parser.add_argument(
    '-H',
    '--height',
    type=int,
    default=80,
    help='可以通过此参数指定图片转换大小到一定高度，单位：像素，默认值：80')
args = parser.parse_args()

IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output

ascii_chars = list(
    "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\
    !@#$%^&*()_+|?><.,:;~`1234567890 "
)
ascii_table = [c * 2 for c in ascii_chars]
TABLE_LENGTH = len(ascii_table)


def getChars(gray):
    if gray == 255:
        return '  '
    else:
        return ascii_table[int(gray / 256 * TABLE_LENGTH)]


if __name__ == '__main__':

    im = Image.open(IMG)
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    im = im.convert('L')
    txt = ''

    for y in range(HEIGHT):
        for x in range(WIDTH):
            gray = int(im.getpixel((x, y)))
            txt += getChars(gray)
        txt += '\n'

    if OUTPUT:
        with open(OUTPUT, 'w') as f:
            f.write(txt)
    else:
        with open('output.txt', 'w') as f:
            f.write(txt)
